package com.szty.lib_pen.oidbluetooth;

import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;

import com.sjh.lib_app.AppApplication;
import com.sjh.lib_app.bean.BleDevBean;
import com.sjh.lib_app.bean.NetBleInfo;
import com.szty.lib_pen.sendPoint.MacSettingHelper;
import com.tqltech.tqlpencomm.BLEException;
import com.tqltech.tqlpencomm.BLEScanner;
import com.tqltech.tqlpencomm.PenCommAgent;
import com.tqltech.tqlpencomm.bean.Dot;
import com.tqltech.tqlpencomm.bean.ElementCode;
import com.tqltech.tqlpencomm.listener.TQLPenSignal;
import com.tqltech.tqlpencomm.util.BLELogUtil;


import java.util.ArrayList;
import java.util.List;

import static com.szty.lib_pen.oidbluetooth.DotUtils.parseDeviceName;


public class BluetoothLEService extends Service {
    private final static String TAG = "BluetoothLEService";
    public static String mBluetoothDeviceAddress = "";
    private String mDeviceBattery = "";
    public final static String ACTION_GATT_CONNECTED = "ACTION_GATT_CONNECTED";
    public final static String ACTION_GATT_DISCONNECTED = "ACTION_GATT_DISCONNECTED";
    public final static String ACTION_PEN_STATUS_CHANGE = "ACTION_PEN_STATUS_CHANGE";

    private PenCommAgent bleManager = PenCommAgent.GetInstance(AppApplication.application);
    private ArrayList<NetBleInfo> netBleList = new ArrayList<>();   //已经配置好的蓝牙
    private ArrayList<BleDevBean> scanBleList = new ArrayList<>();  //当前扫描出来的蓝牙

    public void setAutoConnect(Boolean autoConnect) {
        isAutoConnect = autoConnect;
    }

    private Boolean isAutoConnect = true;

    public void setCanStopScann(boolean canStopScann) {
        isCanStopScann = canStopScann;
    }

    private boolean isCanStopScann = false;
    private Handler handlerThree = new Handler(Looper.getMainLooper());
    private ElementCode mElementcode;

    public boolean isConnectedPen() {
        return bleManager.isConnect();
    }

    public String getmDeviceBattery() {
        return mDeviceBattery;
    }

    private void broadcastUpdate(final String action) {
        final Intent intent = new Intent(action);
        sendBroadcast(intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        initialize();
    }

    public void scanLeDevice() {
        scanBleList.clear();
        if (!onDataReceiveListeners.isEmpty()) {
            for (int e = 0; e < onDataReceiveListeners.size(); e++) {
                onDataReceiveListeners.get(e).refData();
            }
        }
        if (bleManager == null) {
            Log.e(TAG, "当前未初始化蓝牙管理器");
            return;
        }
        bleManager.FindAllDevices(new BLEScanner.OnBLEScanListener() {
            @Override
            public void onScanResult(BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
                Log.e("SunJH", "onScanResult");
                String realName = parseDeviceName(bytes);
                boolean isScanBle;
                BleDevBean bleDevice = new BleDevBean(bluetoothDevice, realName, i + "", true);
                isScanBle = !scanBleList.contains(bleDevice);
                if (isScanBle) {
                    scanBleList.add(bleDevice);
                    if (!onDataReceiveListeners.isEmpty()) {
                        for (int e = 0; e < onDataReceiveListeners.size(); e++) {
                            onDataReceiveListeners.get(e).onBleInfo(bleDevice);
                        }
                    }
                }
            }

            @Override
            public void onScanFailed(BLEException e) {
                Log.e("SunJH", "onScanFailed");
                scanBleList.clear();
                if (!onDataReceiveListeners.isEmpty()) {
                    for (int i = 0; i < onDataReceiveListeners.size(); i++) {
                        onDataReceiveListeners.get(i).refData();
                    }
                }

                if (isCanStopScann) return;
                handlerThree.postDelayed(() -> {
                    scanLeDevice();
                }, 1000);
            }
        });
    }

    public void stopScan() {
        bleManager.stopFindAllDevices();
        isCanStopScann = true;
    }

    public class LocalBinder extends Binder {
        public BluetoothLEService getService() {
            return BluetoothLEService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        close();
    }

    private final IBinder mBinder = new LocalBinder();

    /**
     * Initializes a reference to the local Bluetooth adapter.
     *
     * @return Return true if the initialization is successful.
     */
    public boolean initialize() {
        bleManager.init();
        bleManager.setTQLPenSignalListener(tqlPenInstance);

        if (!bleManager.isSupportBluetooth()) {
            Log.e(TAG, "Unable to Support Bluetooth");
            return false;
        }

        if (!bleManager.isSupportBLE()) {
            Log.e(TAG, "Unable to Support BLE.");
            return false;
        }

        return true;
    }

    public boolean connect(final String mac) {
        StringBuffer sb = new StringBuffer(mac);
        if (!mac.contains(":")) {
            int nowAdd = 1;
            for (int i = 0; i < mac.length(); i++) {
                if (i % 2 == 1 && i != mac.length() - 1) {
                    sb.insert(i + nowAdd, ":");
                    nowAdd++;
                }

            }
        }
        String address = sb.toString();
        if (address == null) {
            return false;
        }

        // Previously connected device.  Try to reconnect.
        if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
                && bleManager.isConnect(address)) {
            return true;
        }

        boolean flag = bleManager.connect(address);
        if (!flag) {
            return false;
        }
        mBluetoothDeviceAddress = address;
        MacSettingHelper.Companion.getInstance().putMac(address);
        return true;
    }

    public void disconnect() {
        if (bleManager == null) return;
        bleManager.disconnect(mBluetoothDeviceAddress);
    }

    public void close() {
        if (bleManager == null) {
            return;
        }

        BLELogUtil.i(TAG, "BluetoothLEService close");
        bleManager.disconnect(mBluetoothDeviceAddress);
        mBluetoothDeviceAddress = "";
        bleManager = null;
    }

    /// ===========================================================
    private ArrayList<OnDataReceiveListener> onDataReceiveListeners = new ArrayList<>();

    public void addOnDataReceiveListener(OnDataReceiveListener dataReceiveListener) {
        for (BleDevBean data : scanBleList) {
            dataReceiveListener.onBleInfo(data);
        }
        int status;
        if (bleManager.isConnect()) {
            status = 1;
        } else {
            status = 2;
        }
        dataReceiveListener.onConnectChange(status);
        onDataReceiveListeners.add(dataReceiveListener);
    }

    public boolean removeDataReceiveListener(OnDataReceiveListener dataReceiveListener) {
        return onDataReceiveListeners.remove(dataReceiveListener);
    }

    private TQLPenSignal tqlPenInstance = new ATQLPenSignal() {

        /**********************************************************/
        /****************** part1: 蓝牙连接相关 *******************/
        /**********************************************************/
        @Override
        public void onConnected() {
            String intentAction;
            intentAction = ACTION_GATT_CONNECTED;
            broadcastUpdate(intentAction);
            stopScan();
            if (!onDataReceiveListeners.isEmpty()) {
                for (int i = 0; i < onDataReceiveListeners.size(); i++) {
                    onDataReceiveListeners.get(i).onConnectChange(1);
                }
            }
        }

        @Override
        public void onDisconnected() {
            String intentAction;
            intentAction = ACTION_GATT_DISCONNECTED;
            broadcastUpdate(intentAction);
            isCanStopScann = false;
            if (!onDataReceiveListeners.isEmpty()) {
                for (int i = 0; i < onDataReceiveListeners.size(); i++) {
                    onDataReceiveListeners.get(i).onConnectChange(2);
                }
            }
        }

        @Override
        public void onConnectFailed() {
            String intentAction;
            intentAction = ACTION_GATT_DISCONNECTED;
            broadcastUpdate(intentAction);
            isCanStopScann = false;
            if (!onDataReceiveListeners.isEmpty()) {
                for (int i = 0; i < onDataReceiveListeners.size(); i++) {
                    onDataReceiveListeners.get(i).onConnectFailed();
                }
            }

        }

        @Override
        public void onReceiveDot(Dot dot) {
            Log.d(TAG, "online:" + dot.toString());
            if (!onDataReceiveListeners.isEmpty()) {
                for (int i = 0; i < onDataReceiveListeners.size(); i++) {
                    onDataReceiveListeners.get(i).onDataReceive(dot);
                }
            }

        }

        @Override
        public void onReceivePenBattery(int penBattery, boolean bIsCharging) {
            Log.e("SunJH", "onReceivePenBattery" + penBattery);
            mDeviceBattery = penBattery + "%";
        }

        /**********************************************************/
        /****************** part6: 上报   *******************/
        /**********************************************************/
        @Override
        public void onReceiveElementCode(ElementCode elementCode) {
            if (mElementcode == null || mElementcode.index != elementCode.index) {
                Log.e(TAG, "onReceiveElementCode: " + elementCode.index);
                String intentAction;
                intentAction = ACTION_PEN_STATUS_CHANGE;
                broadcastUpdate(intentAction);
                mElementcode = elementCode;
                if (!onDataReceiveListeners.isEmpty()) {
                    for (int i = 0; i < onDataReceiveListeners.size(); i++) {
                        onDataReceiveListeners.get(i).onReceiveElementCode(elementCode);
                    }
                }

            }
        }
    };
}

